package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.pojo.system.Resource;
import com.qingcheng.service.system.AdminService;
import com.qingcheng.service.system.ResourceKeyService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证处理器
 */

public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference
    private AdminService adminService;

    @Reference
    private ResourceKeyService resourceKeyService;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名去查询账号密码
        Map map = new HashMap();
        map.put("loginName",s);
        map.put("status","1");
        List<Admin> list = adminService.findList(map);

        //System.out.println("aaaaaaaaaaaaaaaaaaaaa--------------------->"+list);
        //判断有没有查到数据
        if (list.size()==0){
            return null;
        }
        List<GrantedAuthority> grantedAuthorities=new ArrayList<GrantedAuthority>();

        //根据用户名去查询权限列表,控制显示部分菜单
        List<Resource> resources = resourceKeyService.ResourceKey(s);
        for (Resource resource : resources) {
            //grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            grantedAuthorities.add(new SimpleGrantedAuthority(resource.getResKey()));
        }

        return new User(s,list.get(0).getPassword(),grantedAuthorities);
    }
}
